<?php
/* SVN FILE: $Id: skinMasterToCache.php 135 2009-07-27 18:46:08Z supersmashbrothers $ */
/**
* ibMarket
* This file is to convert the master skin files to skin cache files for IPB.
* This file is intended for IP.Board 2.3
* Place this file in the root directory as the forum
*
* @author $Author: supersmashbrothers $
* @copyright $Copyright$
* @version $Revision: 135 $
* @lastrevision $Date: 2009-07-27 18:46:08 +0000 (Mon, 27 Jul 2009) $
* @modifiedby $LastChangedBy: supersmashbrothers $
* @lastmodified $LastChangedDate: 2009-07-27 18:46:08 +0000 (Mon, 27 Jul 2009) $
* @filesource $URL: http://ipb-ibmarket.googlecode.com/svn/ibmarket1/trunk/skinMasterToCache.php $
*/

// Editable Variables

define( 'MASTER_FOLDER' , 1);
$SKIN_TEMPLATES = array();
$SKIN_TEMPLATES[] = 'skin_market';
$SKIN_TEMPLATES[] = 'skin_market_plugin';

// IPB Loading

define( 'IPB_THIS_SCRIPT', 'admin' );
define( 'IPB_LOAD_SQL'   , 'admin_queries' );

require_once( './init.php' );

$INFO = array();

require_once ROOT_PATH   . "sources/ipsclass.php";

if ( file_exists( ROOT_PATH   . "conf_global.php" ) )
{
	require_once ROOT_PATH   . "conf_global.php";
}

$ipsclass       = new ipsclass();
$ipsclass->vars = $INFO;

$Debug = new Debug;
$Debug->startTimer();

$ipsclass->init_db_connection();

$ipsclass->init_cache_setup();
$ipsclass->init_load_cache( array('rss_export', 'bbcode', 'badwords', 'emoticons', 'settings', 'group_cache', 'systemvars', 'skin_id_cache', 'forum_cache', 'moderators', 'stats') );

require_once( ROOT_PATH.'sources/lib/admin_cache_functions.php' );
$ipsclass->cache_func = new admin_cache_functions();
$ipsclass->cache_func->ipsclass =& $ipsclass;

session_start();

switch($_GET['process'])
{
	case 'rebuildCache':
		rebuildCache();
		break;
	case 'rebuildMaster':
	default:
		rebuildMaster();
		break;
}

outputMessages();
session_destroy();

function rebuildMaster()
{
	global $SKIN_TEMPLATES, $ipsclass;
	
	$_SESSION['messages'] = array();
	$skin_dir = CACHE_PATH."cache/skin_cache/cacheid_".MASTER_FOLDER;
	
	foreach($SKIN_TEMPLATES as $name)
	{
		$path = $skin_dir."/".$name.".php";
		if(!file_exists($path))
		{
			$_SESSION['messages'][] = "Cannot find file: ".$path;
			continue;
		}
		
		if(!is_readable($path))
		{
			$_SESSION['messages'][] = "File not readable: ".$path;
			continue;
		}
		
		if ($FH = fopen($path, 'r') )
		{
			$fdata = fread( $FH, filesize($path) );
			fclose($FH);
		}
		else
		{
			$_SESSION['messages'][] = "Cannot open file: ".$path;
			continue;
		}
		
		$fdata = str_replace( "\r", "\n", $fdata );
		$fdata = str_replace( "\n\n", "\n", $fdata );
		
		if ( ! preg_match( "/\n/", $fdata ) )
		{
			$_SESSION['messages'][] = "Could not find any line endings in ".$path.", skipping file...";
			continue;
		}
		
		$_SESSION['messages'][] = "Processing ".$path;
		
		$farray = explode( "\n", $fdata );
		
		//-----------------------------------------
		
		$functions = array();
		$matches = array();
		
		foreach($farray as $f)
		{
			//-----------------------------------------
			// Skip javascript functions...
			//-----------------------------------------
			
			if ( preg_match( "/<script/i", $f ) )
			{
				$script_token = 1;
				$script_jump  = 0;
			}
			
			if ( preg_match( "/<\/script>/i", $f ) )
			{
				$script_token = 0;
				$script_jump  = 0;
			}
			
			//-----------------------------------------
			// If, in the middle?
			//-----------------------------------------
			
			if ( $script_token AND $script_jump == 0 )
			{
				if ( preg_match( "#//startif#", $f ) )
				{
					$script_jump  = 1;
					$script_token = 0;
				}
				
				if ( preg_match( "#<if=[\'\"]#", $f ) )
				{
					$script_jump  = 1;
					$script_token = 0;
				}
			}
			
			if ( $script_token == 0 AND $script_jump == 1 )
			{
				if ( preg_match( "#//endif#", $f ) )
				{
					$script_jump  = 0;
					$script_token = 1;
				}
				
				if ( preg_match( "#</if>#", $f ) )
				{
					$script_jump  = 0;
					$script_token = 1;
				}
			}
			
			//-----------------------------------------
			// NOT IN JS
			//-----------------------------------------
			
			if ( ! $script_token )
			{
				if ( preg_match( "/^function\s*([\w\_]+)\s*\((.*)\)/i", $f, $matches ) )
				{
					$functions[ $matches[1] ]   = '';
					$config[ $matches[1] ]      = $matches[2];
					$flag                       = $matches[1];
					$_SESSION['messages'][] = "Processing function: ".$flag;
					continue;
				}
			}
			//-----------------------------------------
			// ARE IN JS
			//-----------------------------------------
			else
			{
				$f = preg_replace( "#if\s+?\(#is"  , "i~f~(~"   , $f );
				$f = preg_replace( "#else#is"      , "e~lse~"   , $f );
				$f = preg_replace( "#else\s+?if#is", "e~lse~i~f", $f );
			}
			
			if ($flag)
			{
				$functions[$flag] .= $f."\n";
				continue;
			}
			
		}
		
		//-----------------------------------------
		// Remove current templates for this set...
		//-----------------------------------------
		
		$ipsclass->DB->simple_exec_query( array( 'delete' => 'skin_templates', 'where' => "set_id='".MASTER_FOLDER."' AND group_name='$name'" ) );
		
		$flag  = 0;
		
		foreach($functions as $fname => $ftext)
		{
			preg_match( "#//--starthtml--//(.+?)//--endhtml--//#s", $ftext, $matches );
			
			$content = str_replace( '\\n' , '\\\\\\n', $ipsclass->cache_func->template->convert_php_to_html($matches[1]) );
			
			//-----------------------------------------
			// Unconvert JS
			//-----------------------------------------
			
			$content = str_replace( "i~f~(~"   , "if ("   , $content );
			$content = str_replace( "e~lse~"   , "else"   , $content );
			$content = str_replace( "e~lse~i~f", "else if", $content );
			
			$ipsclass->DB->do_insert( 'skin_templates', array (
																	'set_id'          => MASTER_FOLDER,
																	'group_name'      => $name,
																	'section_content' => $content,
																	'func_name'       => $fname,
																	'func_data'       => trim($config[$fname]),
																	'updated'         => time(),
										)       				);
		}
		
		//-----------------------------------------
		// OK, now work in linked template bits
		//-----------------------------------------
		
		$ipsclass->DB->do_delete( 'skin_template_links', 'link_set_id=' . MASTER_FOLDER . " AND link_used_in='" . $name . "'" );
		
		//-----------------------------------------
		// Got template bits?
		//-----------------------------------------
		
		if ( strstr( $fdata, '<__templatebits__>' ) )
		{
			$_templates = array();
			$match = array();
			
			preg_match( "#<__templatebits__>(.+?)</__templatebits__>#is", $fdata, $match );
			
			if ( $match[1] )
			{ 
				preg_match_all( "#<bit>(.+?)</bit>#is", $fdata, $matches );
				
				for ( $i = 0; $i < count( $matches[0] ); $i++)
				{
					list( $file, $_name ) = explode( ':', $matches[1][$i] );
					
					if ( $file AND $_name )
					{
						$_templates[ $file ][] = $_name;
					}
				}
			}
			
			//-----------------------------------------
			// Got stuff to load?
			//-----------------------------------------
			
			if ( is_array( $_templates ) AND count( $_templates ) )
			{
				foreach( array_keys($_templates) as $file )
				{
					foreach( $_templates[ $file ] as $template_bit_name )
					{
						$ipsclass->DB->do_insert( 'skin_template_links', array( 'link_set_id'        => MASTER_FOLDER,
																				'link_group_name'    => $file,
																				'link_template_name' => $template_bit_name,
																				'link_used_in'       => $name ) );
					}
				}
			}
		}
		
		$functions = array();
	}
	
	redirect( "skinMasterToCache.php?process=rebuildCache" );
}	

function rebuildCache()
{
	global $ipsclass;
	
	$justdone = intval($_GET['justdone']);
	$justdone = $justdone ? $justdone : 1;
	
	//-----------------------------------------
	// Get skins
	//-----------------------------------------
	
	$ipsclass->DB->simple_construct( array( 'select' => '*',
								  'from'   => 'skin_sets',
								  'where'  => 'set_skin_set_id > '.$justdone,
								  'order'  => 'set_skin_set_id',
								  'limit'  => array( 0, 1 )
					     )      );
					     
	$ipsclass->DB->simple_exec();
	
	//-----------------------------------------
	// Got a biggun?
	//-----------------------------------------
	
	$r = $ipsclass->DB->fetch_row();
	
	if ( $r['set_skin_set_id'] )
	{
		$ipsclass->cache_func->_rebuild_all_caches( array($r['set_skin_set_id']) );
		
		$_SESSION['messages'][] = "Rebuilt cache for skin set ".$r['set_name'];
		$_SESSION['messages'] = array_merge($_SESSION['messages'],$ipsclass->cache_func->messages);
		
		redirect( "skinMasterToCache.php?process=rebuildCache&justdone=".$r['set_skin_set_id'] );
	}
	else
	{
		$_SESSION['messages'][] = "Finished rebuilding skin cache";
	}
}

function redirect($url)
{
	@header("Location: ".$url);
	exit();
}

function outputMessages()
{
	if(is_array($_SESSION['messages']))
	{
		foreach($_SESSION['messages'] as $message)
		{
			print $message;
			print "\n<br />\n";
		}
	}
}
?>